using ERPWinFormWork.Sales.DTO;
using ERPWinFormWork.Sales.DTO.Output;
using ERPWinFormWork.Sales.ErrorCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace ERPWinFormWork.Sales
{
    public partial class ContracAddForm : Form
    {
        private ApiClient _apiClient;
        private Form1 form1;
        public ContracAddForm(Form1 form1)
        {
            InitializeComponent();
            _apiClient = new ApiClient(AppConfig.ApiBaseUrl);

            GetCustomerSelect();
            ColumnsAdd();
            this.form1 = form1;
        }




        private async void GetCustomerSelect()
        {
            var response = await _apiClient.GetAsync<ERPWinFormWork.Sales.ErrorCode.ApiResponse<List<Customer>>>(
                    endpoint: "Sales/CustomerGet"
                );
            if (response != null && response.code == 200)
            {
                var customerList = new List<Customer>
                {
                    new Customer { id = 0, Customer_Name = "请选择" }
                };
                customerList.AddRange(response.data);
                cboCustomer.DataSource = customerList;
                cboCustomer.DisplayMember = "Customer_Name";
                cboCustomer.ValueMember = "id";
                cboCustomer.SelectedIndex = 0;
            }
        }







        private void skinLabel1_Click(object sender, EventArgs e)
        {

        }

        private void btnStepwiseAdd_Click(object sender, EventArgs e)
        {
            using (ProductAddForm productForm = new ProductAddForm())
            {
                if (productForm.ShowDialog() == DialogResult.OK)
                {


                    // 使用BindingList确保数据变更能实时反映到界面
                    var bindingList = new BindingList<ProductModel>(productForm.SelectedProducts);
                    dgvproduct.DataSource = bindingList;


                    // 给操作列设置"移除"文本
                    foreach (DataGridViewRow row in dgvproduct.Rows)
                    {
                        if (row.DataBoundItem == null) continue; // 跳过空行
                        row.Cells["ColOperation"].Value = "移除";


                    }
                }
            }
        }


        /// <summary>
        /// 初始化表格列（核心修改：添加DataPropertyName关联属性）
        /// </summary>
        private void ColumnsAdd()
        {
            // 使用通用方法添加列，确保列与ProductModel属性关联
            AddTextColumn("Product_Name", "产品名称", "Product_Name");
            AddTextColumn("Product_Number", "产品编号", "Product_Number");
            AddTextColumn("Specification", "规格型号", "Specification");
            AddTextColumn("Finished_Type", "产品类型", "Finished_Type");
            AddTextColumn("Unit", "单位", "Unit");
            AddTextColumn("Tax_Rate", "税率", "Tax_Rate", format: "P2"); // 百分比格式
            AddTextColumn("Untaxed_Price", "原未税价格", "Untaxed_Price", format: "N2"); // 保留2位小数
            AddTextColumn("Price_Including", "原含税价格", "Price_Including", format: "N2");
            AddTextColumn("Sales_Quantity", "数量", "Sales_Quantity", format: "N2");
            AddTextColumn("New_Price", "金额小计", "New_Price", format: "N2");
            //AddTextColumn("Price_Tex", "新含税价格", "Price_Tex", format: "N2");
            AddTextColumn("Particulars_Descr", "备注", "Particulars_Descr", width: 150);
            AddTextColumn("ColOperation", "操作", null, isReadOnly: true, width: 80); // 操作列无绑定属性



            // 注册事件（数量编辑完成后计算折扣）
            dgvproduct.CellEndEdit += dgvproduct_CellEndEdit;
            dgvproduct.CellClick += dgvproduct_CellClick;

            // 设置DataGridView基础属性
            dgvproduct.AutoGenerateColumns = false; // 禁止自动生成列
            dgvproduct.AllowUserToAddRows = false;  // 禁止用户新增行
            dgvproduct.ReadOnly = false;            // 整体可编辑（数量列）
            dgvproduct.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // 整行选择
        }

        /// <summary>
        /// 通用列创建方法（封装重复逻辑，设置DataPropertyName）
        /// </summary>
        private void AddTextColumn(
            string columnName,
            string headerText,
            string dataPropertyName,
            bool isReadOnly = false,
            int width = -1,
            string format = ""
        )
        {
            DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
            column.Name = columnName;
            column.HeaderText = headerText;
            column.ReadOnly = isReadOnly;

            // 关键：关联ProductModel的属性
            if (!string.IsNullOrEmpty(dataPropertyName))
            {
                column.DataPropertyName = dataPropertyName;
            }

            // 设置列宽
            if (width > 0)
            {
                column.Width = width;
            }
            else
            {
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            }

            // 设置数据格式（如价格、百分比）
            if (!string.IsNullOrEmpty(format))
            {
                column.DefaultCellStyle.Format = format;
            }

            dgvproduct.Columns.Add(column);
        }

        /// <summary>
        /// 移除行功能
        /// </summary>
        private void dgvproduct_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 修复1：优先过滤无效行索引（必须放在最前面）
            if (e.RowIndex < 0)
                return; // 点击列标题或空白区域，直接返回

            // 修复2：过滤已删除/无效的行（避免索引超出集合大小）
            if (e.RowIndex >= dgvproduct.Rows.Count)
                return;

            // 修复3：先获取当前行，判断是否有效（避免行已被移除）
            DataGridViewRow currentRow = dgvproduct.Rows[e.RowIndex];
            if (currentRow == null || currentRow.IsNewRow || currentRow.DataBoundItem == null)
                return;

            // 修复4：判断列索引（先检查列是否存在，避免列名错误导致的索引异常）
            DataGridViewColumn operationColumn = dgvproduct.Columns["ColOperation"];
            if (operationColumn == null || e.ColumnIndex != operationColumn.Index)
                return;

            // 修复5：判断"移除"文本（避免空值导致的ToString()异常）
            string cellValue = currentRow.Cells["ColOperation"].Value?.ToString() ?? "";
            if (cellValue != "移除")
                return;

            // 至此，所有条件均有效，执行移除逻辑
            if (dgvproduct.DataSource is BindingList<ProductModel> bindingList)
            {
                // 修复6：强转前判断数据类型，避免转换失败
                if (currentRow.DataBoundItem is ProductModel product)
                {
                    bindingList.Remove(product);

                }
                else
                {
                    MessageBox.Show("当前行数据异常，无法移除产品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            // 兼容非BindingList数据源（兜底逻辑）
            else if (dgvproduct.Rows.Count > e.RowIndex)
            {
                dgvproduct.Rows.RemoveAt(e.RowIndex);
            }
        }

        private async void dgvproduct_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            // 检查是否编辑的是数量列
            if (e.RowIndex < 0 || dgvproduct.Columns[e.ColumnIndex].Name != "Sales_Quantity")
                return;

            var row = dgvproduct.Rows[e.RowIndex];
            if (row.DataBoundItem is ProductModel product)
            {
                // 验证数量是否有效
                if (!decimal.TryParse(row.Cells["Sales_Quantity"].Value?.ToString(), out decimal quantity) || quantity <= 0)
                {
                    MessageBox.Show("请输入有效的数量（大于0的数字）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 验证是否已选择客户
                if (cboCustomer.SelectedValue == null || !int.TryParse(cboCustomer.SelectedValue.ToString(), out int customerId) || customerId <= 0)
                {
                    MessageBox.Show("请先选择客户再计算折扣", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                try
                {

                    var parameters = new Dictionary<string, string>
                {
                    { "ProctorId", product.Id.ToString() },
                    { "CustomerId", customerId.ToString() },
                    { "Price",product.Untaxed_Price.ToString("F2") }, // 保留2位小数
                    { "Number", quantity.ToString("F0") } // 数量按整数传递（根据接口要求调整）
                };

                    var response = await _apiClient.GetAsync<ApiResponse<decimal>>(
               endpoint: "Sales/Discountcomputer",
               parameters: parameters
           );
                    if (response != null && response.code == 200 && response.data >= 0)
                    {
                        var taxRate = product.Tax_Rate;
                        var newTaxedPrice = response.data * (1 + taxRate); // 计算新含税价格

                        // 更新界面显示

                        row.Cells["Untaxed_Price"].Value = response.data;
                        row.Cells["Price_Including"].Value = newTaxedPrice;

                        product.Untaxed_Price = response.data;
                        product.Price_Including = newTaxedPrice;


                        row.Cells["New_Price"].Value = quantity * product.Price_Including;

                         UpdateTotalAmount();

                    }
                    else
                    {



                        // 更新界面和数据源
                        row.Cells["Untaxed_Price"].Value = product.Untaxed_Price;
                        row.Cells["Price_Including"].Value = product.Price_Including;
                        product.Untaxed_Price = product.Untaxed_Price;
                        product.Price_Including = product.Price_Including;

                        row.Cells["New_Price"].Value = quantity * product.Price_Including;
                        UpdateTotalAmount();

                    }
                }
                catch (Exception ex)
                {
                    // 异常处理

                    MessageBox.Show($"计算折扣时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }

        /// <summary>
        /// 计算并更新金额小计的总和
        /// </summary>
        private void UpdateTotalAmount()
        {
            decimal totalAmount = 0;

            foreach (DataGridViewRow row in dgvproduct.Rows)
            {
                // 跳过空行和新增行
                if (row.DataBoundItem == null || row.IsNewRow)
                    continue;

                // 累加金额小计
                if (decimal.TryParse(row.Cells["New_Price"].Value?.ToString(), out decimal rowTotal))
                {
                    totalAmount += rowTotal;
                }
            }

            // 更新总和显示（假设skinTextBox1用于显示总金额）
            skinTextBox1.Text = totalAmount.ToString("F2");
        }

        private void skinButton1_Click(object sender, EventArgs e)
        {
            // 1. 初始化核心对象，提前确保集合非空（避免Add时空引用）
            ContractAddCommand add = new ContractAddCommand();
            add.sales_Contract = new Sales_ContractCommandDTO(); // 关键：初始化集合
            add.contract_Particulars = new List<Contract_ParticularCommandDTO>(); // 关键：初始化集合

            try
            {
                if (cboCustomer.SelectedValue == null
                    || !int.TryParse(cboCustomer.SelectedValue.ToString(), out int customerId)
                    || customerId <= 0)
                {
                    MessageBox.Show("请选择有效的客户（非“请选择”选项）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 合同信息校验
                string contractName = txtQuotationName.Text.Trim();
                string contractNumber = txtQuotationNumber.Text.Trim();
                string address = skinTextBox2.Text.Trim();
                string description = txtQuotationDescr.Text.Trim();
                string file = FIleName;

                if (string.IsNullOrEmpty(contractName))
                {
                    MessageBox.Show("合同名称不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (string.IsNullOrEmpty(contractNumber))
                {
                    MessageBox.Show("合同编号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (string.IsNullOrEmpty(address))
                {
                    MessageBox.Show("送货地址不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 日期校验
                if (!DateTime.TryParse(dtpContractTime.Text.Trim(), out DateTime signedTime))
                {
                    MessageBox.Show("请输入有效的签约日期", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 总金额校验
                if (!decimal.TryParse(skinTextBox1.Text.Trim(), out decimal contractMoney) || contractMoney <= 0)
                {
                    MessageBox.Show("合同总金额必须大于0", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (string.IsNullOrEmpty(file))
                {
                    MessageBox.Show("附件不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 封装主合同信息
                Sales_ContractCommandDTO contract = new Sales_ContractCommandDTO()
                {
                    Customer_Id = customerId,
                    Contract_Name = contractName,
                    Contract_Number = contractNumber,
                    Address = address,
                    Contrac_Descr = description,
                    Contrac_Money = contractMoney,
                    Signed_Time = signedTime,
                     Picture= file
                };
                add.sales_Contract = contract;

                 


                // 产品明细处理
                foreach (DataGridViewRow row in dgvproduct.Rows)
                {
                    if (row.DataBoundItem == null || row.IsNewRow)
                        continue;

                    if (!(row.DataBoundItem is ProductModel product))
                    {
                        MessageBox.Show($"第 {row.Index + 1} 行数据异常，无法识别产品信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    if (product.Id <= 0)
                    {
                        MessageBox.Show($"第 {row.Index + 1} 行产品ID无效（需为正整数）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    // 数量校验
                    if (!int.TryParse(row.Cells["Sales_Quantity"].Value?.ToString()?.Trim(), out int salesQuantity) || salesQuantity <= 0)
                    {
                        MessageBox.Show($"第 {row.Index + 1} 行数量格式错误（需输入大于0的数字）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    // 金额校验
                    if (!decimal.TryParse(row.Cells["New_Price"].Value?.ToString()?.Trim(), out decimal money) || money < 0)
                    {
                        MessageBox.Show($"第 {row.Index + 1} 行金额格式错误（需输入非负数字）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    string particularsDescr = row.Cells["Particulars_Descr"].Value?.ToString()?.Trim() ?? string.Empty;

                    // 封装明细
                    Contract_ParticularCommandDTO item = new Contract_ParticularCommandDTO()
                    {
                        Descr = particularsDescr,
                        Money = money,
                        Price = product.Untaxed_Price,
                        Price_Tex = product.Price_Including,
                        Product_Id = product.Id,
                        Sales_Quantity = salesQuantity
                    };
                    add.contract_Particulars.Add(item);
                }

                if (add.contract_Particulars.Count == 0)
                {
                    MessageBox.Show("请至少添加一条产品明细后再提交", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                Add(add);
            }
            catch (Exception ex)
                {
                    MessageBox.Show($"提交合同时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
        }


        /// <summary>
        /// 发送POST请求
        /// </summary>
        private async void Add(ContractAddCommand discountData)
        {
            var response = await _apiClient.PostAsync<ContractAddCommand, ApiResponse<string>>(
                endpoint: "Sales/ContractAdd",
                data: discountData
            );

            if (response != null && response.code == 200)
            {
                AddPicture();
                MessageBox.Show("销售合同添加成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                form1.GetContractData();
                this.Close();
            }
            else
            {
                MessageBox.Show($"提交失败：{response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void lblQuotationDescr_Click(object sender, EventArgs e)
        {

        }

        private  string FIleName {  get; set; }
        private void btnFile_Click(object sender, EventArgs e)
        {
            // 创建OpenFileDialog实例
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                // 设置对话框的标题
                openFileDialog.Title = "请选择文件";
                // 设置文件筛选器，限定可选择的文件类型
                openFileDialog.Filter =
     "图片文件 (*.jpg;*.png;*.bmp;*.jpeg)|*.jpg;*.png;*.bmp;*.jpeg|" +
     "文本文件 (*.txt)|*.txt|" +
     "所有文件 (*.*)|*.*";
                // 设置默认选中的筛选器索引，这里默认选中第一个（文本文件）
                openFileDialog.FilterIndex = 1;
                // 设置是否恢复到上次打开对话框时的目录，true表示恢复
                openFileDialog.RestoreDirectory = true;
                // 设置是否检查用户输入的文件名是否存在，true表示检查
                openFileDialog.CheckFileExists = true;
                // 设置是否检查用户输入的路径是否存在，true表示检查
                openFileDialog.CheckPathExists = true;

                // 显示对话框，并判断用户是否点击了“确定”按钮
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 获取用户选择的文件路径
                    string selectedFilePath = openFileDialog.FileName;
                    FIleName=openFileDialog.FileName;
                    // 将文件路径显示在文本框中
                    pib1.Image = Image.FromFile(selectedFilePath);
                    
                }
            }
        }


        /// <summary>
        /// 发送POST请求
        /// </summary>
        private async void AddPicture()
        {
            // 检查文件是否存在
            if (!File.Exists(FIleName))
            {
                // 处理文件不存在的情况，比如抛出异常或返回错误响应
                throw new FileNotFoundException("指定的文件不存在", FIleName);
            }

            // 创建 MultipartFormDataContent
            var formData = new MultipartFormDataContent();

            // 读取文件内容并添加到请求体
            using (var fileStream = new FileStream(FIleName, FileMode.Open, FileAccess.Read))
            {
                var fileContent = new StreamContent(fileStream);
                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");

                // 添加文件内容到 formData，参数名需与 API 期望的一致（这里是 "file"）
                formData.Add(fileContent, "file", Path.GetFileName(FIleName));
            }

            // 调用文件上传方法
            var uploadResponse = await _apiClient.UploadFileAsync<ApiResponse<string>>(
                endpoint: "File/UploadFile",
                filePath: FIleName,
                formFieldName: "file" // 与接口接收参数名一致
            );



        }
    }
}
